package com.quyu.service.impl;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.quyu.dto.Result;
import com.quyu.entity.Shop;
import com.quyu.mapper.ShopMapper;
import com.quyu.service.IShopService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.quyu.utils.RedisData;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;


@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Override
    public Result queryById(Long id) {
/*        String shopJson = stringRedisTemplate.opsForValue().get("cache:shop:"+id);
        if(StrUtil.isNotBlank(shopJson)){
            Shop shop = JSONUtil.toBean(shopJson, Shop.class);
            return Result.ok(shop);
        }
        // 缓存穿透,=""
        if(shopJson != null){
            return Result.fail("店铺不存在");
        }
        Shop shop = getById(id);
        if(shop == null){
            stringRedisTemplate.opsForValue().set("cache:shop:"+id,"",2L, TimeUnit.MINUTES);
            return Result.fail("店铺不存在");
        }
        stringRedisTemplate.opsForValue().set("cache:shop:"+id,JSONUtil.toJsonStr(shop),30L, TimeUnit.MINUTES);
        return Result.ok(shop);*/
        Shop shop = queryWithMutex(id);
        if(shop==null){
            return Result.fail("店铺不存在");
        }
        return Result.ok(shop);
    }
    private boolean tryLock(String key){
        boolean flag =stringRedisTemplate.opsForValue().setIfAbsent(key,"1",10L, TimeUnit.SECONDS);

        return BooleanUtil.isTrue(flag);
    }
    private boolean unLock(String key){
        Boolean flag = stringRedisTemplate.delete(key);
        return BooleanUtil.isTrue(flag);

    }
    @Override
    @Transactional
    public Result update(Shop shop) {
        Long id= shop.getId();
        if(id == null){
            return Result.fail("店铺id不能为空");
        }
        updateById(shop);
        stringRedisTemplate.delete("cache:shop:"+shop.getId());

        return null;
    }
    //线程池
    private static final ExecutorService CACHE_REBUILD_EXECUTOR = Executors.newFixedThreadPool(10);
    public Shop queryWithLogic(Long id) throws InterruptedException{
        String shopJson = stringRedisTemplate.opsForValue().get("cache:shop:"+id);
        if(StrUtil.isBlank(shopJson)){

            return null;
        }
        RedisData redisData = JSONUtil.toBean(shopJson, RedisData.class);
        Shop shop = JSONUtil.toBean(shopJson, Shop.class);
        if(redisData.getExpireTime().isAfter(LocalDateTime.now())){
            return shop;
        }

        String lockKey="lock:shop:"+id;
        Boolean isLock = tryLock(lockKey);
        if(isLock){

                CACHE_REBUILD_EXECUTOR.submit(() -> {
                    try {
                        Save2Shop(id, 20L);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }finally{
                        unLock(lockKey);
                    }

                });

        }


        return shop;
    }
    //防止缓存穿透
    public Shop queryWithPassThrough(Long id){
        String shopJson = stringRedisTemplate.opsForValue().get("cache:shop:"+id);
        if(StrUtil.isNotBlank(shopJson)){
            Shop shop = JSONUtil.toBean(shopJson, Shop.class);
            return shop;
        }
        // 缓存穿透,=""
        if(shopJson != null){
            return null;
        }
        Shop shop = getById(id);
        if(shop == null){
            stringRedisTemplate.opsForValue().set("cache:shop:"+id,"",2L, TimeUnit.MINUTES);
            return null;
        }
        stringRedisTemplate.opsForValue().set("cache:shop:"+id,JSONUtil.toJsonStr(shop),30L, TimeUnit.MINUTES);
        return shop;
    }
    //防止缓存击穿
    public Shop queryWithMutex(Long id){
        String shopJson = stringRedisTemplate.opsForValue().get("cache:shop:"+id);
        if(StrUtil.isNotBlank(shopJson)){
            Shop shop = JSONUtil.toBean(shopJson, Shop.class);
            return shop;
        }
        // 缓存穿透,=""
        if(shopJson != null){
            return null;
        }
        String lockKey="lock:shop:"+id;
        try {
            boolean isLock = tryLock(lockKey);
            if (!isLock) {
                Thread.sleep(50);
                return queryWithMutex(id);
            }
            Shop shop = getById(id);
            if (shop == null) {
                stringRedisTemplate.opsForValue().set("cache:shop:" + id, "", 2L, TimeUnit.MINUTES);
                return null;
            }
            stringRedisTemplate.opsForValue().set("cache:shop:" + id, JSONUtil.toJsonStr(shop), 30L, TimeUnit.MINUTES);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }finally {
            unLock(lockKey);
        }
        Shop shop = getById(id);
        return shop;
    }

    public void Save2Shop(Long id,Long expireSeconds) throws InterruptedException {
        Shop shop = getById(id);
        Thread.sleep(200);
        RedisData redisData = new RedisData();
        redisData.setData(shop);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(expireSeconds));
        stringRedisTemplate.opsForValue().set("cache:shop:"+id,JSONUtil.toJsonStr(redisData));
    }


}
